package com.aps.common.model.test;

import com.aps.common.model.APSProductModel;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * APS算法测试数据构建器
 * 专门用于算法测试的便捷数据生成工具
 */
public class APSAlgorithmTestDataBuilder {
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    private APSProductModel model;
    
    public APSAlgorithmTestDataBuilder() {
        this.model = new APSProductModel();
        initializeDefaults();
    }
    
    /**
     * 初始化默认值
     */
    private void initializeDefaults() {
        // 默认产品
        APSProductModel.Product product = new APSProductModel.Product();
        product.setId("TEST-PROD-001");
        product.setName("测试产品");
        product.setModel("TEST-MODEL");
        product.setSpecification("测试规格");
        model.setProduct(product);
        
        // 默认资源
        APSProductModel.Resources resources = new APSProductModel.Resources();
        resources.setEquipment(new ArrayList<>());
        resources.setPersonnel(new ArrayList<>());
        model.setResources(resources);
        
        // 默认工序
        model.setOperations(new ArrayList<>());
        
        // 默认订单
        model.setOrders(new ArrayList<>());
    }
    
    /**
     * 创建新的构建器实例
     */
    public static APSAlgorithmTestDataBuilder create() {
        return new APSAlgorithmTestDataBuilder();
    }
    
    /**
     * 构建最终模型
     */
    public APSProductModel build() {
        return model;
    }
    
    /**
     * 添加订单
     */
    public APSAlgorithmTestDataBuilder addOrder(String orderId, String customerName, 
                                               String productModel, int quantity, 
                                               String deliveryDate, String priority, 
                                               double orderAmount) {
        APSProductModel.ProductionOrder order = new APSProductModel.ProductionOrder();
        order.setId(orderId);
        order.setCustomerName(customerName);
        order.setProductModel(productModel);
        order.setQuantity(quantity);
        order.setDeliveryDate(deliveryDate);
        order.setPriority(priority);
        order.setOrderAmount(orderAmount);
        order.setPriorityScore(calculatePriorityScore(priority, orderAmount));
        order.setCriticalRatio(calculateCriticalRatio(deliveryDate, quantity));
        
        model.getOrders().add(order);
        return this;
    }
    
    /**
     * 添加订单（简化版本）
     */
    public APSAlgorithmTestDataBuilder addOrder(String orderId, int quantity, String priority) {
        return addOrder(orderId, "客户" + orderId, "TEST-MODEL", quantity, 
                       getRandomDeliveryDate(), priority, quantity * 100.0);
    }
    
    /**
     * 添加工序
     */
    public APSAlgorithmTestDataBuilder addOperation(String operationId, String name, 
                                                   int sequence, String equipmentType,
                                                   double standardTime, double setupTime,
                                                   String personnelRequirement, String qualityRequirement) {
        APSProductModel.Operation operation = new APSProductModel.Operation();
        operation.setId(operationId);
        operation.setName(name);
        operation.setSequence(sequence);
        operation.setEquipmentType(equipmentType);
        operation.setStandardTime(standardTime);
        operation.setSetupTime(setupTime);
        operation.setPersonnelRequirement(personnelRequirement);
        operation.setQualityRequirement(qualityRequirement);
        operation.setRequiredResources(Arrays.asList("EQ" + String.format("%03d", sequence)));
        
        model.getOperations().add(operation);
        return this;
    }
    
    /**
     * 添加工序（简化版本）
     */
    public APSAlgorithmTestDataBuilder addOperation(String operationId, String name, int sequence) {
        return addOperation(operationId, name, sequence, name + "设备", 
                          10.0 + sequence * 5, 5.0, "操作员", "标准");
    }
    
    /**
     * 添加设备资源
     */
    public APSAlgorithmTestDataBuilder addEquipment(String equipmentId, String name, 
                                                   String type, double dailyCapacity, 
                                                   double efficiencyFactor) {
        APSProductModel.EquipmentResource equipment = new APSProductModel.EquipmentResource();
        equipment.setId(equipmentId);
        equipment.setName(name);
        equipment.setType(type);
        equipment.setDailyCapacity(dailyCapacity);
        equipment.setEfficiencyFactor(efficiencyFactor);
        equipment.setStatus("正常");
        equipment.setCapabilities(Arrays.asList("精密加工", "批量生产"));
        
        model.getResources().getEquipment().add(equipment);
        return this;
    }
    
    /**
     * 添加设备资源（简化版本）
     */
    public APSAlgorithmTestDataBuilder addEquipment(String equipmentId, String name) {
        return addEquipment(equipmentId, name, "加工设备", 480.0, 0.9);
    }
    
    /**
     * 添加人员资源
     */
    public APSAlgorithmTestDataBuilder addPersonnel(String personnelId, String name, 
                                                   String position, List<String> skills) {
        APSProductModel.PersonnelResource personnel = new APSProductModel.PersonnelResource();
        personnel.setId(personnelId);
        personnel.setName(name);
        personnel.setPosition(position);
        personnel.setJobType(position);
        personnel.setSkillLevel("中级");
        personnel.setDailyWorkHours(8.0);
        personnel.setStatus("在职");
        personnel.setEfficiencyFactor(1.0);
        personnel.setSkills(skills);
        personnel.setOperableEquipment(Arrays.asList("EQ001", "EQ002"));
        
        model.getResources().getPersonnel().add(personnel);
        return this;
    }
    
    /**
     * 添加人员资源（简化版本）
     */
    public APSAlgorithmTestDataBuilder addPersonnel(String personnelId, String name, String position) {
        return addPersonnel(personnelId, name, position, Arrays.asList("设备操作", "质量控制"));
    }
    
    /**
     * 设置产品信息
     */
    public APSAlgorithmTestDataBuilder setProduct(String id, String name, String model) {
        APSProductModel.Product product = new APSProductModel.Product();
        product.setId(id);
        product.setName(name);
        product.setModel(model);
        product.setSpecification("测试规格");
        this.model.setProduct(product);
        return this;
    }
    
    /**
     * 批量添加订单
     */
    public APSAlgorithmTestDataBuilder addOrders(int count, String prefix) {
        for (int i = 1; i <= count; i++) {
            String orderId = prefix + String.format("%03d", i);
            String priority = i % 3 == 0 ? "高" : (i % 3 == 1 ? "中" : "低");
            addOrder(orderId, 100 + i * 50, priority);
        }
        return this;
    }
    
    /**
     * 批量添加工序
     */
    public APSAlgorithmTestDataBuilder addOperations(int count, String prefix) {
        String[] operationNames = {"切割", "钻孔", "组装", "质检", "包装"};
        for (int i = 1; i <= count; i++) {
            String operationId = prefix + String.format("%03d", i);
            String name = operationNames[(i - 1) % operationNames.length];
            addOperation(operationId, name, i);
        }
        return this;
    }
    
    /**
     * 批量添加设备
     */
    public APSAlgorithmTestDataBuilder addEquipments(int count, String prefix) {
        String[] equipmentNames = {"切割机", "钻床", "组装线", "质检台", "包装机"};
        for (int i = 1; i <= count; i++) {
            String equipmentId = prefix + String.format("%03d", i);
            String name = equipmentNames[(i - 1) % equipmentNames.length];
            addEquipment(equipmentId, name);
        }
        return this;
    }
    
    /**
     * 批量添加人员
     */
    public APSAlgorithmTestDataBuilder addPersonnels(int count, String prefix) {
        String[] positions = {"操作工", "技术员", "质检员", "装配工"};
        for (int i = 1; i <= count; i++) {
            String personnelId = prefix + String.format("%03d", i);
            String name = "员工" + i;
            String position = positions[(i - 1) % positions.length];
            addPersonnel(personnelId, name, position);
        }
        return this;
    }
    
    /**
     * 创建SPT算法测试数据
     */
    public static APSProductModel createSPTTestData() {
        return APSAlgorithmTestDataBuilder.create()
            .setProduct("PROD-SPT", "SPT测试产品", "SPT-MODEL")
            .addOrder("ORD001", "客户A", "SPT-MODEL", 100, "2024-01-20", "中", 10000.0)
            .addOrder("ORD002", "客户B", "SPT-MODEL", 150, "2024-01-25", "中", 15000.0)
            .addOrder("ORD003", "客户C", "SPT-MODEL", 80, "2024-01-30", "低", 8000.0)
            .addOrder("ORD004", "客户D", "SPT-MODEL", 200, "2024-02-05", "高", 20000.0)
            .addOrder("ORD005", "客户E", "SPT-MODEL", 120, "2024-02-10", "中", 12000.0)
            .addOperations(4, "OP")
            .addEquipments(4, "EQ")
            .addPersonnels(3, "PER")
            .build();
    }
    
    /**
     * 创建EDD算法测试数据
     */
    public static APSProductModel createEDDTestData() {
        return APSAlgorithmTestDataBuilder.create()
            .setProduct("PROD-EDD", "EDD测试产品", "EDD-MODEL")
            .addOrder("ORD001", "客户A", "EDD-MODEL", 100, "2024-01-15", "中", 10000.0)
            .addOrder("ORD002", "客户B", "EDD-MODEL", 150, "2024-01-20", "中", 15000.0)
            .addOrder("ORD003", "客户C", "EDD-MODEL", 80, "2024-01-25", "低", 8000.0)
            .addOrder("ORD004", "客户D", "EDD-MODEL", 200, "2024-01-30", "高", 20000.0)
            .addOrder("ORD005", "客户E", "EDD-MODEL", 120, "2024-02-05", "中", 12000.0)
            .addOperations(4, "OP")
            .addEquipments(4, "EQ")
            .addPersonnels(3, "PER")
            .build();
    }
    
    /**
     * 创建资源负荷均衡算法测试数据
     */
    public static APSProductModel createResourceLoadBalancingTestData() {
        return APSAlgorithmTestDataBuilder.create()
            .setProduct("PROD-RLB", "资源负荷均衡测试产品", "RLB-MODEL")
            .addOrder("ORD001", "客户A", "RLB-MODEL", 100, "2024-01-20", "高", 10000.0)
            .addOrder("ORD002", "客户B", "RLB-MODEL", 150, "2024-01-25", "中", 15000.0)
            .addOrder("ORD003", "客户C", "RLB-MODEL", 80, "2024-01-30", "低", 8000.0)
            .addOrder("ORD004", "客户D", "RLB-MODEL", 200, "2024-02-05", "高", 20000.0)
            .addOrder("ORD005", "客户E", "RLB-MODEL", 120, "2024-02-10", "中", 12000.0)
            .addOperations(4, "OP")
            .addEquipments(4, "EQ")
            .addPersonnels(3, "PER")
            .build();
    }
    
    /**
     * 创建遗传算法测试数据
     */
    public static APSProductModel createGeneticAlgorithmTestData() {
        return APSAlgorithmTestDataBuilder.create()
            .setProduct("PROD-GA", "遗传算法测试产品", "GA-MODEL")
            .addOrder("ORD001", "客户A", "GA-MODEL", 100, "2024-01-20", "高", 10000.0)
            .addOrder("ORD002", "客户B", "GA-MODEL", 150, "2024-01-25", "中", 15000.0)
            .addOrder("ORD003", "客户C", "GA-MODEL", 80, "2024-01-30", "低", 8000.0)
            .addOrder("ORD004", "客户D", "GA-MODEL", 200, "2024-02-05", "高", 20000.0)
            .addOrder("ORD005", "客户E", "GA-MODEL", 120, "2024-02-10", "中", 12000.0)
            .addOperations(4, "OP")
            .addEquipments(4, "EQ")
            .addPersonnels(3, "PER")
            .build();
    }
    
    /**
     * 创建关键比率算法测试数据
     */
    public static APSProductModel createCriticalRatioTestData() {
        return APSAlgorithmTestDataBuilder.create()
            .setProduct("PROD-CR", "关键比率测试产品", "CR-MODEL")
            .addOrder("ORD001", "客户A", "CR-MODEL", 100, "2024-01-20", "高", 10000.0)
            .addOrder("ORD002", "客户B", "CR-MODEL", 150, "2024-01-25", "中", 15000.0)
            .addOrder("ORD003", "客户C", "CR-MODEL", 80, "2024-01-30", "低", 8000.0)
            .addOrder("ORD004", "客户D", "CR-MODEL", 200, "2024-02-05", "高", 20000.0)
            .addOrder("ORD005", "客户E", "CR-MODEL", 120, "2024-02-10", "中", 12000.0)
            .addOperations(4, "OP")
            .addEquipments(4, "EQ")
            .addPersonnels(3, "PER")
            .build();
    }
    
    /**
     * 创建大规模测试数据
     */
    public static APSProductModel createLargeScaleTestData() {
        return APSAlgorithmTestDataBuilder.create()
            .setProduct("PROD-LARGE", "大规模测试产品", "LARGE-MODEL")
            .addOrders(20, "ORD")
            .addOperations(10, "OP")
            .addEquipments(15, "EQ")
            .addPersonnels(8, "PER")
            .build();
    }
    
    /**
     * 创建资源紧张测试数据
     */
    public static APSProductModel createResourceConstrainedTestData() {
        return APSAlgorithmTestDataBuilder.create()
            .setProduct("PROD-CONSTRAINED", "资源紧张测试产品", "CONSTRAINED-MODEL")
            .addOrders(10, "ORD")
            .addOperations(6, "OP")
            .addEquipments(2, "EQ")  // 只有2台设备
            .addPersonnels(1, "PER") // 只有1个人员
            .build();
    }
    
    /**
     * 计算优先级分数
     */
    private double calculatePriorityScore(String priority, double orderAmount) {
        double baseScore = 0.0;
        switch (priority) {
            case "高": baseScore = 100.0; break;
            case "中": baseScore = 50.0; break;
            case "低": baseScore = 10.0; break;
        }
        return baseScore + orderAmount / 1000.0;
    }
    
    /**
     * 计算关键比率
     */
    private double calculateCriticalRatio(String deliveryDate, int quantity) {
        try {
            LocalDate delivery = LocalDate.parse(deliveryDate, DATE_FORMATTER);
            LocalDate today = LocalDate.now();
            long daysRemaining = java.time.temporal.ChronoUnit.DAYS.between(today, delivery);
            return Math.max(0.1, (double) daysRemaining / quantity);
        } catch (Exception e) {
            return 1.0;
        }
    }
    
    /**
     * 生成随机交期
     */
    private String getRandomDeliveryDate() {
        LocalDate today = LocalDate.now();
        int days = new Random().nextInt(30) + 7; // 未来7-37天
        return today.plusDays(days).format(DATE_FORMATTER);
    }
}
